package ae.pcfc.etks.online.itworx.ehs.web.messaging;

import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import ae.pcfc.etks.online.itworx.ehs.web.delegate.WorkflowDelegate;
import ae.pcfc.etks.online.itworx.ehs.web.entity.OFCRequest;

@Component
public class RequestJmsMessageListener implements SessionAwareMessageListener {


	private JmsTemplate template = null;
	private Logger log = LoggerFactory.getLogger(RequestJmsMessageListener.class);

	public void setTemplate(JmsTemplate template) {
		this.template = template;
	}
	
	private WorkflowDelegate workflowDelegate;

	public void setWorkflowDelegate(WorkflowDelegate workflowDelegate) {
		this.workflowDelegate = workflowDelegate;
	}

	/**
	 * Implementation of <code>MessageListener</code>.
	 */
	@Transactional
	public void onMessage(Message message, Session session) {
		try {

			if (message instanceof BytesMessage) {

				OFCRequest ofcRequest = (OFCRequest) template
						.getMessageConverter().fromMessage(message);

				workflowDelegate.updateOFCRequest(ofcRequest);

			}
		} catch (Exception e) {
			log.error("RequestJmsMessageListener.onMessage() - error happned while getting new message ("+message+")",e);
			throw new DataAccessResourceFailureException("Unexpected Failure",e); 
		}
	}
}